package com.tony.demo.ui.performance.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.puhui.lib.utils.DMLog;
import com.puhui.lib.utils.DensityUtil;
import com.tony.demo.R;
import com.tony.demo.mvp.presenter.impl.BasePresenter;
import com.tony.demo.ui.base.BaseActivity;
import com.tony.demo.utils.glide.GlideUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 图片优化
 */
public class LoadImageActivity extends BaseActivity {

    TextView titleText;
    ListView listView;

    private List<String> imageUrlList;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_load_image;
    }

    protected void initView() {
        listView = findViewById(R.id.list_view);
        titleText = findViewById(R.id.title_text);

        String title = "加载图片";
        titleText.setText(title);

        String[] imageUrls = getResources().getStringArray(R.array.images);
        imageUrlList = Arrays.asList(imageUrls);
        listView.setAdapter(new ListViewAdapter());
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DMLog.e(this.getClass().getCanonicalName(), "url = " + parent.getAdapter().getItem(position));
            }
        });

        getImgFromDrawable();
    }


    /**
     * 测试将图片放入不同文件下后，获取时内存的大小
     */
    private void getImgFromDrawable() {
        BitmapFactory.Options options0 = new BitmapFactory.Options();
//        options0.inDensity = (int) (320 * DensityUtil.getScale(this));  //设置这个会缩小
//        options0.inTargetDensity = (int) (320 * DensityUtil.getScale(this));  //设置这个会放大，改变的是bitmap.getDensity()的结果
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.pyy_p, options0);
        //默认options.inDensity值  mipmap-mdpi 160; hdpi 240; xhdpi 320; xxhdpi 480; xxxhdpi 640
        DMLog.e(this.getClass().getCanonicalName(), "options0.inDensity = " + options0.inDensity);
        //options0.inTargetDensity始终是480（应该跟不同手机相关）  缩放倍数：(inTargetDensity / inDensity)的平方
        DMLog.e(this.getClass().getCanonicalName(), "options0.inTargetDensity = " + options0.inTargetDensity);
        DMLog.e(this.getClass().getCanonicalName(), "bitmap.getDensity() = " + bitmap.getDensity());

        //图片原始大小：23.9K 宽高：426*524    DensityUtil.getScale(this) = 3.0（华为P10）
        //放drawable和mipmap-mdpi目录下的结果：8036064(8M) 宽高：1278 * 1572 * 4
        //放mipmap-xhdpi目录下的结果：2009016(1962K) 宽高：639 * 786 * 4
        //放mipmap-xxhdpi目录下的结果：892896(872K) 宽高：426 * 524 * 4
        DMLog.e(this.getClass().getCanonicalName(), "彭于晏图片大小为：" + bitmap.getByteCount());
        DMLog.e(this.getClass().getCanonicalName(), "彭于晏宽高：" + bitmap.getWidth() + " X " + bitmap.getHeight());
        DMLog.e(this.getClass().getCanonicalName(), "缩放比例为：" + DensityUtil.getScale(this));


        BitmapFactory.Options options = new BitmapFactory.Options();
//        TypedValue value = new TypedValue();
//        getResources().openRawResource(resId, value);
//        options.inTargetDensity = value.density;
        options.inScaled = false;  //禁止缩放，防止因为图片位置放错了导致内存成倍增加
        //在这里的结果：放drawable和mipmap-mdpi目录下的结果：892896(872K) 宽高：426 * 524 * 4
        //在这里的结果：放mipmap-xhdpi目录下的结果：892896(872K) 宽高：426 * 524 * 4
        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.pyy_p, options);
        DMLog.e("2、设置inScaled = false后，彭于晏图片大小为：" + bitmap.getByteCount());
        DMLog.e("2、设置inScaled = false后，彭于晏宽高：" + bitmap.getWidth() + " X " + bitmap.getHeight());

    }

    /**
     * 测试一次加载200张图片对内存的消耗
     */
    private void loadTwoHundredImg() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(1000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < 200; i++) {
                            ImageLoaderUtils.getInstance().loadImage(LoadImageActivity.this, String.valueOf(i), null);
                        }
                    }
                });
            }
        }).start();
    }

    public class ListViewAdapter extends BaseAdapter {
        private ViewHolder viewHolder;

        @Override
        public int getCount() {
            return !isNull() ? imageUrlList.size() : Integer.MAX_VALUE;
        }

        @Override
        public String getItem(int position) {
            return isNull() ? "" : imageUrlList.get(position);
        }

        private boolean isNull() {
            return null == imageUrlList || imageUrlList.size() == 0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.load_image_list_item
                        , parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            }
            viewHolder = (ViewHolder) convertView.getTag();
            ImageLoaderUtils.getInstance().loadImage(parent.getContext(), String.valueOf(position), viewHolder.image);

//            GlideUtils.loadImage(parent.getContext(), R.mipmap.reba, viewHolder.image);

//            loadImageByGlide(parent.getContext(), position, viewHolder.image);

            return convertView;
        }

        private void loadImageByGlide(Context context, int position, ImageView image) {
            String imageUrl = "http://hbimg.b0.upaiyun.com/828e72e2855b51a005732f4e007c58c92417a61e1bcb1-61VzNc_fw658";
            if (!isNull()) {
                imageUrl = imageUrlList.get(position);
            }
            GlideUtils.loadImage(context, imageUrl, viewHolder.image);
        }

        public class ViewHolder {
            ImageView image;

            ViewHolder(View view) {
                image = view.findViewById(R.id.image);
            }
        }
    }
}
